// 配置
const CONFIG = {
  api: "/",
  // 是否使用模拟数据（设置为false时使用真实API）
  useMockData: false,
}

// 状态管理
let downloads = []
let settings = {
  basicSettings: {
    defaultSaveDirectory: "C:\\Downloads",
    maxConcurrentDownloads: 3,
    autoStartDownloads: true,
  },
  networkSettings: {
    proxyEnabled: false,
    proxyUrl: "",
    connectionTimeout: 30,
    retryCount: 3,
  },
  advancedSettings: {
    downloadMode: "segmented",
    defaultFormat: "mp4",
    defaultQuality: "best",
    customHeaders: "",
  },
}
let currentSort = "name"
let currentStatusFilter = "all"
let currentKeywordFilter = ""
let eventSource = null
let currentDetailId = null
let speedChartInstance = null
const speedHistory = {}

// 状态配置
const STATUS_CONFIG = {
    pending: {
        text: '等待中',
        icon: 'ri-time-line',
        color: 'info'
    },
    preparing: {
        text: '准备中',
        icon: 'ri-settings-4-line',
        color: 'info'
    },
    downloading: {
        text: '下载中',
        icon: 'ri-download-line',
        color: 'primary'
    },
    merging: {
        text: '合并中',
        icon: 'ri-file-merge-line',
        color: 'warning'
    },
    completed: {
        text: '已完成',
        icon: 'ri-checkbox-circle-line',
        color: 'success'
    },
    stopped: {
        text: '已停止',
        icon: 'ri-pause-line',
        color: 'warning'
    },
    error: {
        text: '错误',
        icon: 'ri-error-warning-line',
        color: 'error'
    },
    retrying: {
        text: '重试中',
        icon: 'ri-refresh-line',
        color: 'info'
    }
};

// DOM元素
document.addEventListener("DOMContentLoaded", () => {
  initializeTheme()
  initializeNavigation()
  initializeNewDownloadModal()
  initializeSortAndFilter()
  initializeDetailSidebar()
  loadSettings()
  //loadDownloads()
  initializeSSE()
})

// 主题管理
function initializeTheme() {
  const savedTheme = localStorage.getItem("theme") || "light"
  document.documentElement.setAttribute("data-theme", savedTheme)

  const themeToggle = document.getElementById("theme-toggle")
  themeToggle.addEventListener("click", () => {
    const currentTheme = document.documentElement.getAttribute("data-theme")
    const newTheme = currentTheme === "light" ? "dark" : "light"
    document.documentElement.setAttribute("data-theme", newTheme)
    localStorage.setItem("theme", newTheme)
    showNotification("主题已更改", `已切换到${newTheme === "light" ? "浅色" : "深色"}主题`, "info")

    // 如果图表存在，重新绘制以适应新主题
    if (speedChartInstance && currentDetailId) {
      const download = downloads.find((d) => d.id.toString() === currentDetailId.toString())
      if (download) {
        updateSpeedChart(download)
      }
    }
  })
}

// 导航
function initializeNavigation() {
  const navItems = document.querySelectorAll(".nav-item")

  navItems.forEach((item) => {
    item.addEventListener("click", () => {
      const page = item.getAttribute("data-page")
      const title = item.getAttribute("data-title")
      const subTitle = item.querySelector(".nav-link").textContent

      // 更新活动导航
      navItems.forEach((nav) => nav.classList.remove("active"))
      item.classList.add("active")

      // 更新页面标题
      document.getElementById("page-title").textContent = title

      // 显示正确的内容区域
      document.querySelectorAll(".content-section").forEach((section) => {
        section.classList.remove("active")
      })

      const targetSection = document.getElementById(page)
      targetSection.classList.remove("active") // 移除以重置动画

      // 使用setTimeout来触发重绘，然后添加active类以启动动画
      setTimeout(() => {
        targetSection.classList.add("active")
      }, 10)

      // 如果切换到所有任务，加载所有下载
      if (page === "all-tasks") {
        applyFiltersAndSort()
      }
      // 为特定类别加载过滤的下载
      else if (["downloading", "completed", "stopped"].includes(page)) {
        const status = page === "downloading" ? "downloading" : page === "completed" ? "completed" : "stopped"
        filterDownloadsByStatus(status)
      }
    })
  })
}

// 排序和过滤初始化
function initializeSortAndFilter() {
  const sortSelect = document.getElementById("sort-select")
  const statusFilter = document.getElementById("status-filter")
  const keywordFilter = document.getElementById("keyword-filter")

  sortSelect.addEventListener("change", () => {
    currentSort = sortSelect.value
    applyFiltersAndSort()
    showNotification("排序已更改", `下载任务已按${getSortText(currentSort)}排序`, "info")
  })

  statusFilter.addEventListener("change", () => {
    currentStatusFilter = statusFilter.value
    applyFiltersAndSort()
    showNotification("筛选已更改", `显示${getStatusFilterText(currentStatusFilter)}的下载任务`, "info")
  })

  keywordFilter.addEventListener("input", () => {
    currentKeywordFilter = keywordFilter.value.toLowerCase()
    applyFiltersAndSort()
  })
}

function getSortText(sort) {
  switch (sort) {
    case "name":
      return "名称"
    case "status":
      return "状态"
    case "progress":
      return "进度"
    case "createdtime":
      return "创建时间"
    default:
      return sort
  }
}

function getStatusFilterText(filter) {
  switch (filter) {
    case "all":
      return "所有"
    case "downloading":
      return "下载中"
    case "completed":
      return "已完成"
    case "stopped":
      return "已停止"
    case "error":
      return "错误"
    default:
      return filter
  }
}

// 初始化详情侧边栏
function initializeDetailSidebar() {
  const sidebar = document.getElementById("download-detail-sidebar")
  const overlay = document.querySelector(".detail-sidebar-overlay")
  const closeBtn = document.querySelector(".close-detail-btn")
  const copyUrlBtn = document.querySelector(".copy-url-btn")

  // 关闭详情侧边栏
  function closeDetailSidebar() {
    sidebar.classList.remove("active")
    overlay.classList.remove("active")
    currentDetailId = null

    // 如果有图表实例，销毁它
    if (speedChartInstance) {
      speedChartInstance = null
    }
  }

  // 点击关闭按钮
  closeBtn.addEventListener("click", closeDetailSidebar)

  // 点击遮罩层关闭
  overlay.addEventListener("click", closeDetailSidebar)

  // 复制URL按钮
  copyUrlBtn.addEventListener("click", () => {
    const urlText = document.getElementById("detail-url").textContent
    if (urlText && urlText !== "-") {
      navigator.clipboard
        .writeText(urlText)
        .then(() => showNotification("已复制", "URL已复制到剪贴板", "success"))
        .catch((err) => {
          console.error("无法复制URL: ", err)
          showNotification("错误", "无法复制URL", "error")
        })
    }
  })

  // 详情面板中的操作按钮
  document.getElementById("detail-actions").addEventListener("click", (e) => {
    if (e.target.closest(".action-btn")) {
      const actionBtn = e.target.closest(".action-btn")
      const action = actionBtn.getAttribute("data-action")

      if (currentDetailId) {
        handleDownloadAction(action, currentDetailId)
      }
    }
  })
}

// 显示下载详情
function showDownloadDetail(downloadId) {
  const download = downloads.find((d) => d.id.toString() === downloadId.toString())
  if (!download) return

  currentDetailId = downloadId

  // 更新详情面板内容
  updateDetailPanel(download)

  // 显示侧边栏和遮罩
  const sidebar = document.getElementById("download-detail-sidebar")
  const overlay = document.querySelector(".detail-sidebar-overlay")

  sidebar.classList.add("active")
  overlay.classList.add("active")
}

// 更新详情面板内容
function updateDetailPanel(download) {
  // 基本信息
  document.getElementById("detail-name").textContent = download.name

  const statusBadge = document.getElementById("detail-status")
  statusBadge.textContent = getStatusText(download.status)
  statusBadge.className = "detail-value status-badge " + download.status

  document.getElementById("detail-url").textContent = download.url

  // 格式化日期时间
  const createdDate = new Date(download.createdtime)
  const updatedDate = new Date(download.updatedtime)
  document.getElementById("detail-created").textContent = formatDateTime(createdDate)
  document.getElementById("detail-updated").textContent = formatDateTime(updatedDate)

  // 进度信息
  const progressPercent = download.total > 0 ? Math.round((download.completed / download.total) * 100) : 0
  document.getElementById("detail-progress-bar").style.width = `${progressPercent}%`
  document.getElementById("detail-progress-percent").textContent = `${progressPercent}%`
  document.getElementById("detail-progress-segments").textContent = `${download.completed}/${download.total} 片段`

  // 统计信息
  document.getElementById("detail-speed").textContent = formatSpeed(download.speed)
  document.getElementById("detail-size").textContent = formatSize(download.size)

  // 计算剩余时间
  let etaText = "--:--"
  if (download.status === "downloading" && download.speed > 0) {
    const remainingBytes = download.size * (1 - progressPercent / 100)
    const etaSeconds = remainingBytes / download.speed
    etaText = formatETA(etaSeconds)
  }
  document.getElementById("detail-eta").textContent = etaText

  // 下载设置
  document.getElementById("detail-dir").textContent = download.dir || settings.basicSettings.defaultSaveDirectory
  document.getElementById("detail-format").textContent = download.format ? download.format.toUpperCase() : "默认"
  document.getElementById("detail-quality").textContent = download.quality || "默认"
  document.getElementById("detail-mode").textContent =
    download.download_mode === "segmented" ? "分段下载" : download.download_mode === "ffmpeg" ? "FFmpeg" : "默认"
  document.getElementById("detail-proxy").textContent = download.proxy || "未使用"

  // 错误信息
  const errorSection = document.getElementById("error-section")
  if (download.message) {
    document.getElementById("detail-error").textContent = download.message
    errorSection.style.display = "block"
  } else {
    errorSection.style.display = "none"
  }

  // 速度图表
  const speedChartSection = document.getElementById("speed-chart-section")
  if (download.status === "downloading") {
    speedChartSection.style.display = "block"
    updateSpeedChart(download)
  } else {
    speedChartSection.style.display = "none"
  }

  // 操作按钮
  const actionsContainer = document.getElementById("detail-actions")
  actionsContainer.innerHTML = getDetailActionButtons(download)
}

// 获取详情面板的操作按钮
function getDetailActionButtons(download) {
  let buttons = ""

  // 开始/暂停按钮
  if (download.status === "downloading") {
    buttons += `
      <button class="action-btn pause" data-action="pause" title="暂停">
        <i class="ri-pause-line"></i>
        <span>暂停</span>
      </button>
    `
  } else if (download.status === "stopped" || download.status === "error") {
    buttons += `
      <button class="action-btn resume" data-action="resume" title="继续">
        <i class="ri-play-line"></i>
        <span>继续</span>
      </button>
    `
  }

  // 错误时的重试按钮
  if (download.status === "error") {
    buttons += `
      <button class="action-btn retry" data-action="retry" title="重试">
        <i class="ri-refresh-line"></i>
        <span>重试</span>
      </button>
    `
  }

  // 删除按钮
  buttons += `
    <button class="action-btn delete" data-action="delete" title="删除">
      <i class="ri-delete-bin-line"></i>
      <span>删除</span>
    </button>
  `

  return buttons
}

// 更新速度图表
function updateSpeedChart(download) {
  const canvas = document.getElementById("speed-chart")
  const ctx = canvas.getContext("2d")

  // 清除画布
  ctx.clearRect(0, 0, canvas.width, canvas.height)

  // 获取速度历史数据
  const speedData = speedHistory[download.id] || []
  if (speedData.length === 0) return

  // 计算最大速度值，用于缩放
  const maxSpeed = Math.max(...speedData) * 1.2

  // 设置图表样式
  const chartWidth = canvas.width
  const chartHeight = canvas.height
  const padding = 30
  const graphWidth = chartWidth - padding * 2
  const graphHeight = chartHeight - padding * 2

  // 绘制网格和坐标轴
  ctx.strokeStyle = getComputedStyle(document.documentElement).getPropertyValue("--chart-grid-color")
  ctx.lineWidth = 0.5

  // 水平网格线
  for (let i = 0; i <= 4; i++) {
    const y = padding + (graphHeight / 4) * i
    ctx.beginPath()
    ctx.moveTo(padding, y)
    ctx.lineTo(padding + graphWidth, y)
    ctx.stroke()

    // 速度标签
    const speedValue = maxSpeed - (maxSpeed / 4) * i
    ctx.fillStyle = getComputedStyle(document.documentElement).getPropertyValue("--text-secondary")
    ctx.font = "10px sans-serif"
    ctx.textAlign = "right"
    ctx.fillText(formatSpeed(speedValue), padding - 5, y + 3)
  }

  // 垂直网格线
  const timePoints = Math.min(10, speedData.length)
  for (let i = 0; i <= timePoints; i++) {
    const x = padding + (graphWidth / timePoints) * i
    ctx.beginPath()
    ctx.moveTo(x, padding)
    ctx.lineTo(x, padding + graphHeight)
    ctx.stroke()

    // 时间标签
    if (i % 2 === 0) {
      const timeAgo = (timePoints - i) * 2
      ctx.fillStyle = getComputedStyle(document.documentElement).getPropertyValue("--text-secondary")
      ctx.font = "10px sans-serif"
      ctx.textAlign = "center"
      ctx.fillText(`${timeAgo}秒前`, x, padding + graphHeight + 15)
    }
  }

  // 绘制速度曲线
  ctx.strokeStyle = getComputedStyle(document.documentElement).getPropertyValue("--chart-line-color")
  ctx.lineWidth = 2
  ctx.beginPath()

  speedData.forEach((speed, index) => {
    const x = padding + (graphWidth / (speedData.length - 1)) * index
    const y = padding + graphHeight - (speed / maxSpeed) * graphHeight

    if (index === 0) {
      ctx.moveTo(x, y)
    } else {
      ctx.lineTo(x, y)
    }
  })

  ctx.stroke()

  // 填充曲线下方区域
  const gradient = ctx.createLinearGradient(0, padding, 0, padding + graphHeight)
  gradient.addColorStop(0, getComputedStyle(document.documentElement).getPropertyValue("--primary-light"))
  gradient.addColorStop(1, "rgba(255, 255, 255, 0)")

  ctx.fillStyle = gradient
  ctx.beginPath()

  // 起点
  ctx.moveTo(padding, padding + graphHeight)

  // 绘制与上面相同的路径
  speedData.forEach((speed, index) => {
    const x = padding + (graphWidth / (speedData.length - 1)) * index
    const y = padding + graphHeight - (speed / maxSpeed) * graphHeight

    if (index === 0) {
      ctx.lineTo(x, y)
    } else {
      ctx.lineTo(x, y)
    }
  })

  // 闭合路径
  ctx.lineTo(padding + graphWidth, padding + graphHeight)
  ctx.closePath()
  ctx.fill()
}

// 格式化日期时间
function formatDateTime(date) {
  if (!(date instanceof Date) || isNaN(date)) return "-"

  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, "0")
  const day = String(date.getDate()).padStart(2, "0")
  const hours = String(date.getHours()).padStart(2, "0")
  const minutes = String(date.getMinutes()).padStart(2, "0")
  const seconds = String(date.getSeconds()).padStart(2, "0")

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 格式化剩余时间
function formatETA(seconds) {
  if (seconds < 0 || !isFinite(seconds)) return "--:--"

  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = Math.floor(seconds % 60)

  if (hours > 0) {
    return `${hours}:${String(minutes).padStart(2, "0")}:${String(secs).padStart(2, "0")}`
  } else {
    return `${minutes}:${String(secs).padStart(2, "0")}`
  }
}

// 新建下载对话框
function initializeNewDownloadModal() {
  const newDownloadBtn = document.getElementById("new-download-btn")
  const modal = document.getElementById("new-download-modal")
  const closeBtn = modal?.querySelector(".close-btn")
  const cancelBtn = modal?.querySelector(".cancel-btn")
  const startDownloadBtn = document.getElementById("start-download-btn")
  const useProxyCheckbox = document.getElementById("use-proxy")
  const proxyInput = document.querySelector(".proxy-input")
  const urlInput = document.getElementById("download-url")

  // 检查必要的元素是否存在
  if (!newDownloadBtn || !modal || !closeBtn || !cancelBtn || !startDownloadBtn || 
      !useProxyCheckbox || !proxyInput || !urlInput) {
    console.error("新建下载对话框所需的DOM元素未找到")
    return
  }

  // 打开对话框
  newDownloadBtn.addEventListener("click", () => {
    modal.style.display = "block"
    document.body.style.overflow = "hidden" // 防止背景滚动

    // 用默认设置填充字段
    const downloadDir = document.getElementById("download-dir")
    const downloadFormat = document.getElementById("download-format")
    const downloadQuality = document.getElementById("download-quality")
    const downloadModeSelect = document.getElementById("download-mode-select")
    const proxyInput = document.getElementById("proxy-input")
    const customHeadersInput = document.getElementById("custom-headers-input")

    if (downloadDir) downloadDir.value = settings.basicSettings.defaultSaveDirectory
    if (downloadFormat) downloadFormat.value = ""
    if (downloadQuality) downloadQuality.value = ""
    if (downloadModeSelect) downloadModeSelect.value = ""
    if (useProxyCheckbox) useProxyCheckbox.checked = settings.networkSettings.proxyEnabled
    if (proxyInput) proxyInput.value = settings.networkSettings.proxyUrl
    if (customHeadersInput) customHeadersInput.value = settings.advancedSettings.customHeaders

    // 根据复选框显示/隐藏代理输入
    proxyInput.style.display = useProxyCheckbox.checked ? "block" : "none"

    // 聚焦URL输入框
    setTimeout(() => urlInput.focus(), 100)
  })

  // 关闭对话框
  closeBtn.addEventListener("click", () => {
    modal.style.display = "none"
    document.body.style.overflow = ""
  })

  cancelBtn.addEventListener("click", () => {
    modal.style.display = "none"
    document.body.style.overflow = ""
  })

  // 切换代理输入
  useProxyCheckbox.addEventListener("change", () => {
    proxyInput.style.display = useProxyCheckbox.checked ? "block" : "none"
  })

  // 提交下载
  startDownloadBtn.addEventListener("click", () => {
    if (!urlInput.value.trim()) {
      showNotification("错误", "请输入有效的M3U8 URL", "error")
      urlInput.focus()
      return
    }

    // 处理多个URL（每行一个）
    const urls = urlInput.value.split("\n").filter((url) => url.trim() !== "")

    // 显示加载中通知
    const loadingNotificationId = showNotification("处理中", `正在添加 ${urls.length} 个下载任务...`, "info", 0)

    // 为每个URL创建下载任务
    const addDownloadPromises = urls.map((url) => {
      return addDownload({
        url: url.trim(),
        name: document.getElementById("download-name")?.value.trim() || "",
        dir: document.getElementById("download-dir")?.value.trim() || "",
        format: document.getElementById("download-format")?.value || "",
        quality: document.getElementById("download-quality")?.value || "",
        download_mode: document.getElementById("download-mode-select")?.value || "",
        proxy: useProxyCheckbox.checked ? document.getElementById("proxy-input")?.value.trim() || "" : "",
        headers: document.getElementById("custom-headers-input")?.value.trim() || "",
      })
    })

    Promise.all(addDownloadPromises)
      .then(() => {
        removeNotification(loadingNotificationId)
        showNotification("成功", `已添加 ${urls.length} 个下载任务`, "success")
        modal.style.display = "none"
        document.body.style.overflow = ""
        urlInput.value = ""
        document.getElementById("download-name").value = ""
        loadDownloads()
      })
      .catch((error) => {
        removeNotification(loadingNotificationId)
        showNotification("错误", `添加下载时出错: ${error.message}`, "error")
      })
  })

  // 点击外部关闭对话框
  window.addEventListener("click", (event) => {
    if (event.target === modal) {
      modal.style.display = "none"
      document.body.style.overflow = ""
    }
  })

  // 添加表单验证
  urlInput.addEventListener("input", function () {
    if (this.value.trim() === "") {
      this.classList.add("invalid")
    } else {
      this.classList.remove("invalid")
    }
  })
}

// 应用过滤器和排序
function applyFiltersAndSort() {
  // 首先应用状态过滤器
  let filtered = downloads
  if (currentStatusFilter !== "all") {
    filtered = filtered.filter((download) => download.status === currentStatusFilter)
  }

  // 然后应用关键词过滤器
  if (currentKeywordFilter) {
    filtered = filtered.filter((download) => {
      return (
        download.name.toLowerCase().includes(currentKeywordFilter) ||
        download.url.toLowerCase().includes(currentKeywordFilter)
      )
    })
  }

  // 最后应用排序
  filtered.sort((a, b) => {
    switch (currentSort) {
      case "name":
        return a.name.localeCompare(b.name)
      case "status":
        return a.status.localeCompare(b.status)
      case "progress":
        const progressA = a.total > 0 ? a.completed / a.total : 0
        const progressB = b.total > 0 ? b.completed / b.total : 0
        return progressB - progressA // 降序排列
      case "createdtime":
        return new Date(b.createdtime) - new Date(a.createdtime) // 降序排列
      default:
        return 0
    }
  })

  renderDownloads(filtered)
}

function filterDownloadsByStatus(status) {
  const filtered = downloads.filter((download) => download.status === status)
  renderDownloads(filtered)
}

// 渲染下载
function renderDownloads(downloadsList) {
  const downloadContainer = document.getElementById("download-list")
 // downloadContainer.innerHTML = ""

  if (downloadsList.length === 0) {
    downloadContainer.innerHTML = `
            <div class="empty-state">
                <div class="empty-state-icon"><i class="ri-inbox-line"></i></div>
                <div class="empty-state-text">未找到下载任务。开始新的下载以在此处查看。</div>
            </div>
        `
    return
  }

  downloadsList.forEach((download) => {
    // 判断列表是否存在，如果已经存在，采取更新的方式
    const existingItem = document.querySelector(`[data-id="${download.id}"]`)
    const progressPercent = download.total > 0 ? Math.round((download.completed / download.total) * 100) : 0

    if (existingItem) {
      // 如果状态为delete，直接移除
      if (download.status === "delete") {
        existingItem.remove()
        return
      }
      // 更新状态      
      const statusBadge = existingItem.querySelector(".download-status")
      statusBadge.textContent = getStatusText(download.status)
      statusBadge.className = "download-status " + download.status
      // 更新进度条
      const progressBar = existingItem.querySelector(".download-progress-inner")
      progressBar.style.width = progressPercent + "%"
      // 更新剩余时间
      const etaText = formatETA(download.speed > 0? (download.size - download.completed) / download.speed : 0)
      const progressText = existingItem.querySelector(".download-progress-text span:first-child")
      progressText.textContent = etaText
      // 更新错误消息
      const errorMessage = existingItem.querySelector(".error-message")
      if (download.message) {
        if (!errorMessage) {
          const errorMessageElement = document.createElement("div")
          errorMessageElement.className = "error-message"
          errorMessageElement.textContent = download.message
          existingItem.appendChild(errorMessageElement)
        }  else {
          errorMessage.textContent = download.message
        }
      }
      // 更新速度图表
      if (download.status === "downloading") {
        const speedChartSection = existingItem.querySelector("#speed-chart-section")
        if (speedChartSection) {
          speedChartSection.style.display = "block"
          updateSpeedChart(download)
        }
      }else {
        if (errorMessage) {
          errorMessage.remove()
        }
      }
      // 跳过 渲染
      return
    }

    const downloadItem = document.createElement("div")
    downloadItem.className = `download-item ${download.message ? "has-error" : ""} ${download.status}`
    downloadItem.setAttribute("data-id", download.id)

    // 格式化显示值
    const formattedSize = formatSize(download.size)
    const formattedSpeed = formatSpeed(download.speed)

    // 基于状态的状态图标
    const statusIcon = getStatusIcon(download.status)

    // 格式信息徽章
    const formatInfo = download.format ? `${download.format.toUpperCase()}` : ""
    const qualityInfo = download.quality ? ` / ${download.quality}` : ""
    const formatBadge =
      formatInfo || qualityInfo ? `<span class="download-info-badge">${formatInfo}${qualityInfo}</span>` : ""

    downloadItem.innerHTML = `
            <div class="download-item-header">
                <div class="download-title">
                <span class="download-status ${download.status}">
                    <i class="ri-${statusIcon}"></i>
                    ${getStatusText(download.status)}
                </span>
                    ${download.name}
                    ${formatBadge}
                </div>                
                <div class="download-actions">
                    ${getActionButtons(download)}
                </div>
            </div>
            <div class="download-details">
                <div class="download-detail tooltip">
                    <i class="ri-dashboard-line"></i>
                    <span>${formattedSpeed}</span>
                    <span class="tooltip-text">下载速度</span>
                </div>
                <div class="download-detail tooltip">
                    <i class="ri-hard-drive-line"></i>
                    <span>${formattedSize}</span>
                    <span class="tooltip-text">文件大小</span>
                </div>
                <div class="download-detail tooltip">
                    <i class="ri-stack-line"></i>
                    <span>${download.completed}/${download.total} 片段</span>
                    <span class="tooltip-text">片段</span>
                </div>
            </div>
            <div class="download-progress-container">
                <div class="download-progress-bar">
                    <div class="download-progress-inner" style="width: ${progressPercent}%"></div>
                </div>
                <div class="download-progress-text">
                    <span>${formatETA(download.speed > 0? (download.size - download.completed) / download.speed : 0)}</span>
                    <span>${progressPercent}% 完成</span>
                </div>
            </div>            
            ${download.message ? `<div class="error-message">${download.message}</div>` : ""}
        `

    downloadContainer.appendChild(downloadItem)

    // 为操作按钮添加事件监听器
    const actionButtons = downloadItem.querySelectorAll(".action-btn")
    actionButtons.forEach((button) => {
      button.addEventListener("click", (e) => {
        e.stopPropagation()
        const action = button.getAttribute("data-action")
        const downloadId = downloadItem.getAttribute("data-id")
        handleDownloadAction(action, downloadId)
      })
    })

    // 添加点击事件以显示详情
    downloadItem.addEventListener("click", () => {
      const downloadId = downloadItem.getAttribute("data-id")
      showDownloadDetail(downloadId)
    })
  })

  // 同时更新过滤列表
  updateFilteredLists(downloadsList)
}

function updateFilteredLists(allDownloads) {
  // 更新下载中列表
  const downloadingList = document.getElementById("downloading-list")
  const downloadingItems = allDownloads.filter((d) => d.status === "downloading")

  if (downloadingItems.length === 0) {
    downloadingList.innerHTML = `
            <div class="empty-state">
                <div class="empty-state-icon"><i class="ri-loader-line"></i></div>
                <div class="empty-state-text">没有正在进行的下载</div>
            </div>
        `
  } else {
    renderDownloadList(downloadingList, downloadingItems)
  }

  // 更新已完成列表
  const completedList = document.getElementById("completed-list")
  const completedItems = allDownloads.filter((d) => d.status === "completed")

  if (completedItems.length === 0) {
    completedList.innerHTML = `
            <div class="empty-state">
                <div class="empty-state-icon"><i class="ri-checkbox-circle-line"></i></div>
                <div class="empty-state-text">没有已完成的下载</div>
            </div>
        `
  } else {
    renderDownloadList(completedList, completedItems)
  }

  // 更新已停止列表
  const stoppedList = document.getElementById("stopped-list")
  const stoppedItems = allDownloads.filter((d) => d.status === "stopped" || d.status === "error")

  if (stoppedItems.length === 0) {
    stoppedList.innerHTML = `
            <div class="empty-state">
                <div class="empty-state-icon"><i class="ri-pause-circle-line"></i></div>
                <div class="empty-state-text">没有已停止的下载</div>
            </div>
        `
  } else {
    renderDownloadList(stoppedList, stoppedItems)
  }
}

// 渲染特定列表的下载项
function renderDownloadList(container, items) {
  container.innerHTML = ""
  items.forEach((download) => {
    const progressPercent = download.total > 0 ? Math.round((download.completed / download.total) * 100) : 0
    const formattedSize = formatSize(download.size)
    const formattedSpeed = formatSpeed(download.speed)
    const statusIcon = getStatusIcon(download.status)

    const downloadItem = document.createElement("div")
    downloadItem.className = `download-item ${download.message ? "has-error" : ""} ${download.status}`
    downloadItem.setAttribute("data-id", download.id)

    // 格式信息徽章
    const formatInfo = download.format ? `${download.format.toUpperCase()}` : ""
    const qualityInfo = download.quality ? ` / ${download.quality}` : ""
    const formatBadge =
      formatInfo || qualityInfo ? `<span class="download-info-badge">${formatInfo}${qualityInfo}</span>` : ""

    downloadItem.innerHTML = `
      <div class="download-item-header">
        <div class="download-title">
          ${download.name}
          ${formatBadge}
        </div>
        <div class="download-status ${download.status}">
          <i class="ri-${statusIcon}"></i>
          ${getStatusText(download.status)}
        </div>
      </div>
      <div class="download-details">
        <div class="download-detail tooltip">
          <i class="ri-dashboard-line"></i>
          <span>${formattedSpeed}</span>
          <span class="tooltip-text">下载速度</span>
        </div>
        <div class="download-detail tooltip">
          <i class="ri-hard-drive-line"></i>
          <span>${formattedSize}</span>
          <span class="tooltip-text">文件大小</span>
        </div>
        <div class="download-detail tooltip">
          <i class="ri-stack-line"></i>
          <span>${download.completed}/${download.total} 片段</span>
          <span class="tooltip-text">片段</span>
        </div>
      </div>
      <div class="download-progress-container">
        <div class="download-progress-bar">
          <div class="download-progress-inner" style="width: ${progressPercent}%"></div>
        </div>
        <div class="download-progress-text">
          <span>${progressPercent}% 完成</span>
          <span>${download.completed}/${download.total} 片段</span>
        </div>
      </div>
      <div class="download-actions">
        ${getActionButtons(download)}
      </div>
      ${download.message ? `<div class="error-message">${download.message}</div>` : ""}
    `

    container.appendChild(downloadItem)

    // 为操作按钮添加事件监听器
    const actionButtons = downloadItem.querySelectorAll(".action-btn")
    actionButtons.forEach((button) => {
      button.addEventListener("click", (e) => {
        e.stopPropagation()
        const action = button.getAttribute("data-action")
        const downloadId = downloadItem.getAttribute("data-id")
        handleDownloadAction(action, downloadId)
      })
    })

    // 添加点击事件以显示详情
    downloadItem.addEventListener("click", () => {
      const downloadId = downloadItem.getAttribute("data-id")
      showDownloadDetail(downloadId)
    })
  })
}

// 辅助函数
function getStatusIcon(status) {
  return STATUS_CONFIG[status]?.icon || 'ri-question-line';
}

function getStatusText(status) {
  return STATUS_CONFIG[status]?.text || status;
}

function getStatusColor(status) {
  return STATUS_CONFIG[status]?.color || 'default';
}

function getActionButtons(download) {
  let buttons = ""

  // 开始/暂停按钮
  if (download.status === "downloading") {
    buttons += `
            <button class="action-btn pause tooltip" data-action="pause" title="暂停">
                <i class="ri-pause-line"></i>
                <span class="tooltip-text">暂停下载</span>
            </button>
        `
  } else if (download.status === "stopped") {
    buttons += `
            <button class="action-btn resume tooltip" data-action="resume" title="继续">
                <i class="ri-play-line"></i>
                <span class="tooltip-text">继续下载</span>
            </button>
        `
  } else if (download.status === "pending") {
    buttons += `
            <button class="action-btn resume tooltip" data-action="resume" title="开始">
                <i class="ri-play-line"></i>
                <span class="tooltip-text">开始下载</span>
            </button>
        `
  }

  // 错误时的重试按钮
  if (download.status === "error") {
    buttons += `
            <button class="action-btn retry tooltip" data-action="retry" title="重试">
                <i class="ri-refresh-line"></i>
                <span class="tooltip-text">重试下载</span>
            </button>
        `
  }

  // 复制链接按钮
  buttons += `
        <button class="action-btn copy tooltip" data-action="copy" title="复制链接">
            <i class="ri-file-copy-line"></i>
            <span class="tooltip-text">复制URL</span>
        </button>
    `

  // 删除按钮
  buttons += `
        <button class="action-btn delete tooltip" data-action="delete" title="删除">
            <i class="ri-delete-bin-line"></i>
            <span class="tooltip-text">删除下载</span>
        </button>
    `

  return buttons
}

function formatSize(bytes) {
  if (!bytes || bytes === 0) return "0 B"
  const sizes = ["B", "KB", "MB", "GB", "TB"]
  const i = Math.floor(Math.log(bytes) / Math.log(1024))
  return (bytes / Math.pow(1024, i)).toFixed(2) + " " + sizes[i]
}

function formatSpeed(bytesPerSecond) {
  if (bytesPerSecond === 0) return '0 B/s';
  const units = ['B/s', 'KB/s', 'MB/s', 'GB/s'];
  const i = Math.floor(Math.log(bytesPerSecond) / Math.log(1024));
  return `${(bytesPerSecond / Math.pow(1024, i)).toFixed(2)} ${units[i]}`;
}

// 通知系统
let notificationCounter = 0

function showNotification(title, message, type = "info", duration = 5000) {
  const notificationId = `notification-${notificationCounter++}`
  const notificationContainer = document.getElementById("notification-container")

  const notification = document.createElement("div")
  notification.className = `notification ${type}`
  notification.id = notificationId

  let iconClass = "information-line"
  switch (type) {
    case "success":
      iconClass = "checkbox-circle-line"
      break
    case "error":
      iconClass = "error-warning-line"
      break
    case "warning":
      iconClass = "alert-line"
      break
    case "info":
      iconClass = "information-line"
      break
  }

  notification.innerHTML = `
    <div class="notification-icon">
      <i class="ri-${iconClass}"></i>
    </div>
    <div class="notification-content">
      <div class="notification-title">${title}</div>
      <div class="notification-message">${message}</div>
    </div>
    <button class="notification-close">
      <i class="ri-close-line"></i>
    </button>
    ${duration > 0 ? '<div class="notification-progress"></div>' : ""}
  `

  notificationContainer.appendChild(notification)

  // 添加关闭按钮事件
  const closeBtn = notification.querySelector(".notification-close")
  closeBtn.addEventListener("click", () => {
    removeNotification(notificationId)
  })

  // 如果设置了持续时间，则自动关闭
  if (duration > 0) {
    setTimeout(() => {
      removeNotification(notificationId)
    }, duration)
  }

  return notificationId
}

function removeNotification(id) {
  const notification = document.getElementById(id)
  if (notification) {
    notification.style.animation = "slideDown 0.3s ease forwards"
    setTimeout(() => {
      notification.remove()
    }, 300)
  }
}

// API函数
function loadDownloads() {
  const loadingNotificationId = showNotification("加载中", "正在获取下载任务列表...", "info", 0)

  fetch(`${CONFIG.api}api/task`)
    .then((response) => {
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`)
      }
      return response.json()
    })
    .then((data) => {
      removeNotification(loadingNotificationId)
      if (data.code === 200 && Array.isArray(data.data)) {
        downloads = data.data
        applyFiltersAndSort()
        showNotification("已更新", "下载任务列表已更新", "success", 3000)
      } else {
        console.error("API返回了无效数据:", data)
        showNotification("错误", "API返回了无效数据", "error")
      }
    })
    .catch((error) => {
      removeNotification(loadingNotificationId)
      console.error("加载下载时出错:", error)
      showNotification("错误", `加载下载时出错: ${error.message}`, "error")
    })
}

function loadSettings() {
  fetch(`${CONFIG.api}api/settings`)
    .then((response) => {
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`)
      }
      return response.json()
    })
    .then((data) => {
      if (data.code === 200) {
        settings = data.data
        applySettingsToUI(settings)
      } else {
        throw new Error(data.message || "加载设置失败")
      }
    })
    .catch((error) => {
      console.error("加载设置时出错:", error)
      showNotification("错误", `加载设置时出错: ${error.message}`, "error")
    })
}

function applySettingsToUI(settings) {
  // 基本设置
  document.getElementById("default-save-directory").value = settings.basicSettings.defaultSaveDirectory;
  document.getElementById("max-concurrent-downloads").value = settings.basicSettings.maxConcurrentDownloads;
  document.getElementById("auto-start-downloads").checked = settings.basicSettings.autoStartDownloads;

  // 网络设置
  document.getElementById("proxy-enabled").checked = settings.networkSettings.proxyEnabled;
  document.getElementById("proxy-url").value = settings.networkSettings.proxyUrl;
  document.getElementById("connection-timeout").value = settings.networkSettings.connectionTimeout;
  document.getElementById("retry-count").value = settings.networkSettings.retryCount;

  // 高级设置
  document.getElementById("download-mode").value = settings.advancedSettings.downloadMode;
  document.getElementById("default-format").value = settings.advancedSettings.defaultFormat;
  document.getElementById("default-quality").value = settings.advancedSettings.defaultQuality;
  document.getElementById("custom-headers").value = settings.advancedSettings.customHeaders;

  // 设置保存设置的事件监听器
  document.getElementById("save-basic-settings").addEventListener("click", saveBasicSettings)
  document.getElementById("save-network-settings").addEventListener("click", saveNetworkSettings)
  document.getElementById("save-advanced-settings").addEventListener("click", saveAdvancedSettings)
}

function saveBasicSettings() {
  const loadingNotificationId = showNotification("保存中", "正在保存基本设置...", "info", 0);

  const updatedSettings = {
    basicSettings: {
      defaultSaveDirectory: document.getElementById("default-save-directory").value,
      maxConcurrentDownloads: parseInt(document.getElementById("max-concurrent-downloads").value),
      autoStartDownloads: document.getElementById("auto-start-downloads").checked
    }
  };

  saveSettings(updatedSettings, loadingNotificationId, "基本设置");
}

function saveNetworkSettings() {
  const loadingNotificationId = showNotification("保存中", "正在保存网络设置...", "info", 0);

  const updatedSettings = {
    networkSettings: {
      proxyEnabled: document.getElementById("proxy-enabled").checked,
      proxyUrl: document.getElementById("proxy-url").value,
      connectionTimeout: parseInt(document.getElementById("connection-timeout").value),
      retryCount: parseInt(document.getElementById("retry-count").value)
    }
  };

  saveSettings(updatedSettings, loadingNotificationId, "网络设置");
}

function saveAdvancedSettings() {
  const loadingNotificationId = showNotification("保存中", "正在保存高级设置...", "info", 0);

  const updatedSettings = {
    advancedSettings: {
      downloadMode: document.getElementById("download-mode").value,
      defaultFormat: document.getElementById("default-format").value,
      defaultQuality: document.getElementById("default-quality").value,
      customHeaders: document.getElementById("custom-headers").value
    }
  };

  saveSettings(updatedSettings, loadingNotificationId, "高级设置");
}

function saveSettings(updatedSettings, notificationId, settingType) {
  fetch(`${CONFIG.api}api/settings`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify(updatedSettings)
  })
    .then(response => {
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
      }
      return response.json();
    })
    .then(data => {
      removeNotification(notificationId);
      if (data.code === 200) {
        // 更新本地设置
        Object.assign(settings, updatedSettings);
        showNotification("成功", `${settingType}已保存`, "success");
      } else {
        throw new Error(data.message || "保存设置失败");
      }
    })
    .catch(error => {
      removeNotification(notificationId);
      console.error("保存设置时出错:", error);
      showNotification("错误", `保存${settingType}时出错: ${error.message}`, "error");
    });
}

function addDownload(downloadData) {
  return fetch(`${CONFIG.api}api/add`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(downloadData),
  })
    .then((response) => {
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`)
      }
      return response.json()
    })
    .then((data) => {
      if (data.code === 200) {
        return data
      } else {
        throw new Error(data.message || "添加下载失败")
      }
    })
}

function handleDownloadAction(action, downloadId) {
  const downloadItem = downloads.find((d) => d.id.toString() === downloadId)
  if (!downloadItem) return

  switch (action) {
    case "pause":
      stopDownload(downloadId)
      break
    case "resume":
    case "retry":
      resumeDownload(downloadId)
      break
    case "copy":
      navigator.clipboard
        .writeText(downloadItem.url)
        .then(() => showNotification("已复制", "URL已复制到剪贴板", "success"))
        .catch((err) => {
          console.error("无法复制URL: ", err)
          showNotification("错误", "无法复制URL", "error")
        })
      break
    case "delete":
      confirmDelete(downloadId, downloadItem.name)
      break
    default:
      console.warn("未知操作:", action)
  }
}

function confirmDelete(downloadId, downloadName) {
  // 创建确认对话框
  const confirmDialog = document.createElement("div")
  confirmDialog.className = "modal"
  confirmDialog.style.display = "block"

  confirmDialog.innerHTML = `
    <div class="modal-content" style="width: 400px;">
      <div class="modal-header">
        <h2><i class="ri-alert-  style="width: 400px;">
      <div class="modal-header">
        <h2><i class="ri-alert-line" style="color: var(--error-color);"></i> 确认删除</h2>
        <button class="close-btn">&times;</button>
      </div>
      <div class="modal-body">
        <p>您确定要删除以下下载任务吗？</p>
        <p style="font-weight: bold; margin-top: 10px;">${downloadName}</p>
        <p style="margin-top: 10px; color: var(--text-secondary);">此操作无法撤销。</p>
      </div>
      <div class="modal-footer">
        <button id="confirm-delete-btn" class="primary-btn" style="background-color: var(--error-color);">
          <i class="ri-delete-bin-line"></i>
          <span>删除</span>
        </button>
        <button class="secondary-btn cancel-delete-btn">
          <i class="ri-close-line"></i>
          <span>取消</span>
        </button>
      </div>
    </div>
  `

  document.body.appendChild(confirmDialog)
  document.body.style.overflow = "hidden"

  // 添加事件监听器
  const closeBtn = confirmDialog.querySelector(".close-btn")
  const cancelBtn = confirmDialog.querySelector(".cancel-delete-btn")
  const confirmBtn = confirmDialog.querySelector("#confirm-delete-btn")

  const closeDialog = () => {
    confirmDialog.remove()
    document.body.style.overflow = ""
  }

  closeBtn.addEventListener("click", closeDialog)
  cancelBtn.addEventListener("click", closeDialog)

  confirmBtn.addEventListener("click", () => {
    closeDialog()
    deleteDownload(downloadId)

    // 如果当前正在查看该下载的详情，关闭详情面板
    if (currentDetailId === downloadId) {
      const sidebar = document.getElementById("download-detail-sidebar")
      const overlay = document.querySelector(".detail-sidebar-overlay")
      sidebar.classList.remove("active")
      overlay.classList.remove("active")
      currentDetailId = null
    }
  })

  // 点击外部关闭对话框
  confirmDialog.addEventListener("click", (event) => {
    if (event.target === confirmDialog) {
      closeDialog()
    }
  })
}

function stopDownload(downloadId) {
  const loadingNotificationId = showNotification("处理中", "正在停止下载...", "info", 0)

  fetch(`${CONFIG.api}api/stop`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ id: downloadId }),
  })
    .then((response) => {
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`)
      }
      return response.json()
    })
    .then((data) => {
      removeNotification(loadingNotificationId)
      if (data.code === 200) {
        showNotification("成功", "下载已停止", "success")
        // 更新将通过SSE进行
        const downloadIndex = downloads.findIndex((d) => d.id.toString() === downloadId)
        if (downloadIndex !== -1) {
          downloads[downloadIndex].status = "stopped"
          downloads[downloadIndex].speed = 0

          if (currentDetailId === downloadId) {
            updateDetailPanel(downloads[downloadIndex])
          }

          applyFiltersAndSort()
        }
      } else {
        throw new Error(data.message || "停止下载失败")
      }
    })
    .catch((error) => {
      removeNotification(loadingNotificationId)
      console.error("停止下载时出错:", error)
      showNotification("错误", `停止下载时出错: ${error.message}`, "error")
    })
}

function resumeDownload(downloadId) {
  const loadingNotificationId = showNotification("处理中", "正在恢复下载...", "info", 0)

  fetch(`${CONFIG.api}api/resume`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ id: downloadId }),
  })
    .then((response) => {
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`)
      }
      return response.json()
    })
    .then((data) => {
      removeNotification(loadingNotificationId)
      if (data.code === 200) {
        showNotification("成功", "下载已恢复", "success")
        // 更新将通过SSE进行
        const downloadIndex = downloads.findIndex((d) => d.id.toString() === downloadId)
        if (downloadIndex !== -1) {
          downloads[downloadIndex].status = "downloading"
          downloads[downloadIndex].speed = 0

          if (currentDetailId === downloadId) {
            updateDetailPanel(downloads[downloadIndex])
          }

          applyFiltersAndSort()
        }
      } else {
        throw new Error(data.message || "恢复下载失败")
      }
    })
    .catch((error) => {
      removeNotification(loadingNotificationId)
      console.error("恢复下载时出错:", error)
      showNotification("错误", `恢复下载时出错: ${error.message}`, "error")
    })
}

function deleteDownload(downloadId) {
  const loadingNotificationId = showNotification("处理中", "正在删除下载...", "info", 0)

  fetch(`${CONFIG.api}api/del`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ id: downloadId }),
  })
    .then((response) => {
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`)
      }
      return response.json()
    })
    .then((data) => {
      removeNotification(loadingNotificationId)
      if (data.code === 200) {
        showNotification("成功", "下载已删除", "success")
        downloads = downloads.filter((d) => d.id.toString() !== downloadId)
        applyFiltersAndSort()
      } else {
        throw new Error(data.message || "删除下载失败")
      }
    })
    .catch((error) => {
      removeNotification(loadingNotificationId)
      console.error("删除下载时出错:", error)
      showNotification("错误", `删除下载时出错: ${error.message}`, "error")
    })
}

// SSE用于实时更新
function initializeSSE() {
  const eventSource = new EventSource('/api/events');
  let reconnectAttempts = 0;
  const maxReconnectAttempts = 5;
  const reconnectDelay = 5000; // 5秒
  
  // 处理更新事件
  eventSource.addEventListener('update', function(event) {
    try {
      const data = JSON.parse(event.data);
      if (data.downloads) {
        downloads = data.downloads;
        applyFiltersAndSort();
        /*data.downloads.forEach(download => {
          //updateDownloadItem(download);
        });*/
      }
    } catch (error) {
      console.error('SSE数据解析错误:', error);
    }
  });
  
  // 处理心跳事件
  eventSource.addEventListener('heartbeat', function(event) {
    try {
      const data = JSON.parse(event.data);
      console.debug('SSE心跳:', data.timestamp);
    } catch (error) {
      console.error('SSE心跳解析错误:', error);
    }
  });
  
  // 处理错误事件
  eventSource.addEventListener('error', function(event) {
    try {
      const data = JSON.parse(event.data);
      console.error('SSE错误:', data.message);
      
      // 如果是致命错误，关闭连接
      if (data.message.includes('达到最大重试次数')) {
        eventSource.close();
        return;
      }
    } catch (error) {
      console.error('SSE错误事件解析错误:', error);
    }
  });
  
  // 处理连接错误
  eventSource.onerror = function(error) {
    console.error('SSE连接错误:', error);
    eventSource.close();
    
    // 重连逻辑
    if (reconnectAttempts < maxReconnectAttempts) {
      reconnectAttempts++;
      console.log(`尝试重连 (${reconnectAttempts}/${maxReconnectAttempts})...`);
      setTimeout(initSSE, reconnectDelay);
    } else {
      console.error('达到最大重连次数，停止重连');
      // 可以在这里添加用户提示
      showNotification('错误', '与服务器的连接已断开，请刷新页面重试', 'error');
    }
  };
  
  // 页面关闭时清理
  window.addEventListener('beforeunload', function() {
    eventSource.close();
  });
}